<template>
  <div class="info-query-export">
    <!-- 查询条件 -->
    <div class="query-section">
      <div class="section-header">
        <i class="el-icon-search"></i>
        <span>查询条件</span>
      </div>
      <div class="query-form">
        <div class="form-item">
          <label>事件名称</label>
          <el-input 
            v-model="queryParams.eventName" 
            placeholder="请输入事件名称"
            clearable
          ></el-input>
        </div>

        <div class="form-item">
          <label>事件类型</label>
          <el-select v-model="queryParams.eventType" placeholder="请选择事件类型" style="width: 100%" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="传染病疫情" value="传染病疫情"></el-option>
            <el-option label="食品安全事件" value="食品安全事件"></el-option>
            <el-option label="职业中毒" value="职业中毒"></el-option>
            <el-option label="环境污染" value="环境污染"></el-option>
            <el-option label="其他事件" value="其他事件"></el-option>
          </el-select>
        </div>

        <div class="form-item">
          <label>发生时间</label>
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </div>

        <div class="form-item">
          <label>发生地点</label>
          <el-input 
            v-model="queryParams.location" 
            placeholder="请输入发生地点"
            clearable
          ></el-input>
        </div>

        <div class="form-item">
          <label>报告人</label>
          <el-input 
            v-model="queryParams.reporter" 
            placeholder="请输入报告人"
            clearable
          ></el-input>
        </div>

        <div class="form-item">
          <label>处理状态</label>
          <el-select v-model="queryParams.status" placeholder="请选择处理状态" style="width: 100%" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="初步处置" value="初步处置"></el-option>
            <el-option label="持续处理中" value="持续处理中"></el-option>
            <el-option label="基本控制" value="基本控制"></el-option>
            <el-option label="完全控制" value="完全控制"></el-option>
            <el-option label="后续观察" value="后续观察"></el-option>
          </el-select>
        </div>

        <div class="query-buttons">
          <el-button 
            type="default" 
            @click="handleReset"
            style="flex: 1;"
          >
            重置
          </el-button>
          <el-button 
            type="primary" 
            icon="el-icon-search"
            @click="handleQuery"
            style="flex: 2;"
          >
            查询
          </el-button>
        </div>
      </div>
    </div>

    <!-- 查询结果 -->
    <div class="result-section">
      <div class="section-header">
        <i class="el-icon-tickets"></i>
        <span>查询结果（{{ queryResults.length }}）</span>
        <el-button 
          v-if="selectedRecords.length > 0"
          type="text" 
          @click="selectAll = !selectAll; toggleSelectAll()"
          style="margin-left: auto; color: white;"
        >
          {{ selectAll ? '取消全选' : '全选' }}
        </el-button>
      </div>
      
      <div v-if="queryResults.length === 0" class="empty-result">
        <i class="el-icon-search"></i>
        <p>暂无查询结果</p>
        <p class="tip">请输入查询条件后点击查询</p>
      </div>

      <div v-else class="result-list">
        <div 
          v-for="record in queryResults" 
          :key="record.id"
          class="result-item"
          :class="{ selected: isSelected(record.id) }"
          @click="toggleSelect(record.id)"
        >
          <div class="item-checkbox">
            <i :class="isSelected(record.id) ? 'el-icon-success' : 'el-icon-circle-check'"></i>
          </div>
          
          <div class="item-content">
            <div class="item-header">
              <div class="item-title">{{ record.eventName }}</div>
              <el-tag :type="getStatusType(record.status)" size="mini">
                {{ record.status }}
              </el-tag>
            </div>
            
            <div class="item-meta">
              <div class="meta-row">
                <i class="el-icon-s-flag"></i>
                <span>{{ record.eventType }}</span>
              </div>
              <div class="meta-row">
                <i class="el-icon-time"></i>
                <span>{{ record.occurTime }}</span>
              </div>
            </div>
            
            <div class="item-meta">
              <div class="meta-row">
                <i class="el-icon-location"></i>
                <span>{{ record.location }}</span>
              </div>
              <div class="meta-row">
                <i class="el-icon-user"></i>
                <span>{{ record.reporter }}</span>
              </div>
            </div>

            <div class="item-stats">
              <div class="stat">
                <span class="stat-label">累计病例</span>
                <span class="stat-value">{{ record.totalCases }}</span>
              </div>
              <div class="stat">
                <span class="stat-label">在治</span>
                <span class="stat-value">{{ record.treatmentCount }}</span>
              </div>
              <div class="stat">
                <span class="stat-label">治愈</span>
                <span class="stat-value">{{ record.curedCount }}</span>
              </div>
              <div class="stat">
                <span class="stat-label">死亡</span>
                <span class="stat-value">{{ record.deathCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 导出设置 -->
    <div v-if="selectedRecords.length > 0" class="export-section">
      <div class="section-header">
        <i class="el-icon-download"></i>
        <span>导出设置</span>
      </div>
      
      <div class="export-form">
        <div class="form-item">
          <label>导出格式</label>
          <div class="format-options">
            <div 
              v-for="format in exportFormats" 
              :key="format.value"
              class="format-card"
              :class="{ active: exportParams.format === format.value }"
              @click="exportParams.format = format.value"
            >
              <i :class="format.icon"></i>
              <span>{{ format.label }}</span>
            </div>
          </div>
        </div>

        <div class="form-item">
          <label>导出内容</label>
          <el-checkbox-group v-model="exportParams.fields">
            <div class="field-list">
              <el-checkbox label="基本信息">基本信息</el-checkbox>
              <el-checkbox label="人员数据">人员数据</el-checkbox>
              <el-checkbox label="事件描述">事件描述</el-checkbox>
              <el-checkbox label="防控措施">防控措施</el-checkbox>
              <el-checkbox label="处理情况">处理情况</el-checkbox>
              <el-checkbox label="报告人信息">报告人信息</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>

        <div class="selected-info">
          <i class="el-icon-info"></i>
          <span>已选择 {{ selectedRecords.length }} 条记录</span>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button 
        type="primary" 
        size="large"
        icon="el-icon-download"
        @click="handleExport"
        :disabled="selectedRecords.length === 0"
      >
        导出选中记录（{{ selectedRecords.length }}）
      </el-button>
    </div>
  </div>
</template>

<script>
import { queryEventReports, exportEventReports } from './service';

export default {
  name: 'InfoQueryExport',
  
  data() {
    return {
      queryParams: {
        eventName: '',
        eventType: '',
        dateRange: null,
        location: '',
        reporter: '',
        status: ''
      },
      
      queryResults: [],
      selectedRecords: [],
      selectAll: false,
      
      exportParams: {
        format: 'Excel',
        fields: ['基本信息', '人员数据', '事件描述', '防控措施']
      },
      
      exportFormats: [
        { value: 'Excel', label: 'Excel', icon: 'el-icon-s-grid' },
        { value: 'PDF', label: 'PDF', icon: 'el-icon-document' },
        { value: 'Word', label: 'Word', icon: 'el-icon-edit-outline' },
        { value: 'Text', label: '文本', icon: 'el-icon-tickets' }
      ]
    };
  },

  methods: {
    handleQuery() {
      const loading = this.$loading({
        lock: true,
        text: '查询中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      queryEventReports(this.queryParams)
        .then(data => {
          loading.close();
          this.queryResults = data;
          this.selectedRecords = [];
          this.selectAll = false;
          
          if (data.length === 0) {
            this.$message.info('未查询到符合条件的记录');
          } else {
            this.$message.success(`查询到 ${data.length} 条记录`);
          }
        })
        .catch(error => {
          loading.close();
          this.$message.error(error.message || '查询失败');
        });
    },

    handleReset() {
      this.queryParams = {
        eventName: '',
        eventType: '',
        dateRange: null,
        location: '',
        reporter: '',
        status: ''
      };
      this.queryResults = [];
      this.selectedRecords = [];
      this.$message.info('查询条件已重置');
    },

    toggleSelect(id) {
      const index = this.selectedRecords.indexOf(id);
      if (index > -1) {
        this.selectedRecords.splice(index, 1);
      } else {
        this.selectedRecords.push(id);
      }
    },

    isSelected(id) {
      return this.selectedRecords.includes(id);
    },

    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedRecords = this.queryResults.map(r => r.id);
      } else {
        this.selectedRecords = [];
      }
    },

    getStatusType(status) {
      const typeMap = {
        '初步处置': 'info',
        '持续处理中': 'warning',
        '基本控制': 'primary',
        '完全控制': 'success',
        '后续观察': 'success'
      };
      return typeMap[status] || 'info';
    },

    handleExport() {
      if (this.selectedRecords.length === 0) {
        this.$message.warning('请至少选择一条记录');
        return;
      }
      
      if (this.exportParams.fields.length === 0) {
        this.$message.warning('请至少选择一个导出字段');
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: '导出中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      const data = {
        ids: this.selectedRecords,
        format: this.exportParams.format,
        fields: this.exportParams.fields
      };

      exportEventReports(data)
        .then((result) => {
          loading.close();
          this.$notify({
            title: '✅ 导出成功',
            message: `${this.selectedRecords.length} 条记录已导出`,
            type: 'success',
            duration: 2000,
            position: 'top-right',
            offset: 60
          });
          
          // 模拟文件下载
          this.downloadFile(result.fileName);
        })
        .catch(error => {
          loading.close();
          this.$message.error(error.message || '导出失败');
        });
    },

    downloadFile(fileName) {
      // 生成导出文件内容
      let content = `续报信息导出报告\n`;
      content += `=`.repeat(60) + '\n\n';
      content += `导出时间：${new Date().toLocaleString('zh-CN')}\n`;
      content += `导出记录数：${this.selectedRecords.length} 条\n`;
      content += `导出格式：${this.exportParams.format}\n\n`;
      content += `=`.repeat(60) + '\n\n';

      const selectedData = this.queryResults.filter(r => this.selectedRecords.includes(r.id));
      
      selectedData.forEach((record, index) => {
        content += `【记录 ${index + 1}】\n`;
        content += `-`.repeat(60) + '\n';
        
        if (this.exportParams.fields.includes('基本信息')) {
          content += `事件名称：${record.eventName}\n`;
          content += `事件类型：${record.eventType}\n`;
          content += `发生时间：${record.occurTime}\n`;
          content += `发生地点：${record.location}\n`;
        }
        
        if (this.exportParams.fields.includes('人员数据')) {
          content += `累计病例：${record.totalCases}\n`;
          content += `在治人数：${record.treatmentCount}\n`;
          content += `治愈人数：${record.curedCount}\n`;
          content += `死亡人数：${record.deathCount}\n`;
        }
        
        if (this.exportParams.fields.includes('处理情况')) {
          content += `处理状态：${record.status}\n`;
        }
        
        if (this.exportParams.fields.includes('报告人信息')) {
          content += `报告人：${record.reporter}\n`;
        }
        
        content += `\n`;
      });

      content += `=`.repeat(60) + '\n';
      content += '报告结束\n';

      // 创建下载
      const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }
  }
};
</script>

<style scoped>
.info-query-export {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 80px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 查询条件 */
.query-section {
  background: white;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  align-items: center;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.section-header i {
  font-size: 20px;
  margin-right: 8px;
}

.query-form {
  padding: 15px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-item label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.query-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

/* 查询结果 */
.result-section {
  background: white;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.empty-result {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-result i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 15px;
}

.empty-result p {
  margin: 5px 0;
  font-size: 14px;
}

.empty-result .tip {
  font-size: 12px;
  color: #ccc;
}

.result-list {
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-item {
  display: flex;
  align-items: flex-start;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.result-item.selected {
  background: #e7f4ff;
  border-color: #409EFF;
}

.result-item:active {
  transform: scale(0.98);
}

.item-checkbox {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
  margin-top: 2px;
}

.item-checkbox i {
  font-size: 20px;
  color: #409EFF;
}

.result-item:not(.selected) .item-checkbox i {
  color: #ddd;
}

.item-content {
  flex: 1;
  min-width: 0;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.item-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 10px;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.meta-row {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.meta-row i {
  margin-right: 5px;
  color: #409EFF;
}

.item-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

.stat {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 11px;
  color: #999;
  margin-bottom: 3px;
}

.stat-value {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

/* 导出设置 */
.export-section {
  background: white;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.export-form {
  padding: 15px;
}

.format-options {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.format-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.format-card.active {
  background: #e7f4ff;
  border-color: #409EFF;
}

.format-card i {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 5px;
}

.format-card span {
  font-size: 12px;
  color: #666;
}

.field-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.selected-info {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 8px;
  margin-top: 15px;
  color: #409EFF;
  font-size: 13px;
}

.selected-info i {
  margin-right: 8px;
  font-size: 16px;
}

/* 操作按钮 */
.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.action-buttons .el-button {
  width: 100%;
  border-radius: 6px;
  font-size: 15px;
  height: 46px;
  font-weight: 500;
}
</style>

